/* eslint-disable */

import {createAction} from 'redux-actions';
import * as Ajax from '../util/ajax';
import {buildApi} from '../renderers/renderer.jsx';

export const createAjaxAction = (preferMethod, remote, startType, endType) => (values = null, ctx = values) => {
  const ctxGetter = ctx ? () => ctx : null;
  const start = createAction(startType, null, ctxGetter);
  const end = createAction(endType, null, ctxGetter);

  return dispatch => {
    dispatch(start(values));

    const api = buildApi(remote, values, preferMethod);
    const args = [api.url];
    const config = {};
    let data = api.appended && api.data || !api.appended && values;

    if (data && api.dataType === 'form-data' && !~'get|delete'.indexOf(api.method)) {
      const fd = new FormData();
      Object.keys(values).forEach(key => fd.append(key, data[key]));
      data = fd;
    }

    if (~'get|delete'.indexOf(api.method)) {
      config.params = data;
    } else {
      args.push(data);
    }

    args.push(config);
    return dispatch(end(Ajax[api.method].apply(this, args)));
  };
};
